<template>
  <!--包赔端 回收订单 -->
  <div class="app-container backorder_page">
    <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form-new" label-width="90px">
      <!-- <el-form-item label="游戏类型" prop="type">
            <el-select v-model="queryParams.type" placeholder="请选择游戏"  clearable @change="search">
              <el-option v-for="dict in dict.type.game_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item> -->
      <el-form-item label="包赔客服" prop="no">
        <el-select filterable clearable v-model="queryParams.guaranteeId" placeholder="请选择包赔客服" >
          <el-option v-for="(item ,key) in yuangongList" :key="key" :label="item.nickName" :value="item.userId" />
        </el-select>
      </el-form-item>
      <el-form-item label="回收订单号" prop="no">
        <el-input v-model="queryParams.no" placeholder="请输入回收订单号" clearable />
      </el-form-item>
      <el-form-item label="游戏账号" prop="accountNumber">
        <el-input v-model="queryParams.accountNumber" placeholder="请输入游戏账号" clearable />
      </el-form-item>
      <el-form-item label="游戏名称" prop="gameId">
        <el-select v-model="queryParams.gameId" placeholder="请选择游戏" clearable>
          <el-option v-for="dict in gameList" :key="dict.id" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="时间" prop="">
        <el-date-picker clearable v-model="timer" value-format="yyyy-MM-dd" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="成交时间" prop="" v-show="actived == '交易成功'">
            <el-date-picker v-model="successTimer" value-format="yyyy-MM-dd" type="daterange" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="失败时间" prop="" v-show="actived == '交易失败'">
            <el-date-picker v-model="errorTimer" value-format="yyyy-MM-dd" type="daterange" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item> -->
      <el-form-item class="btns">
        <el-button type="primary" icon="el-icon-search" @click="search" class="zdy-btn">搜索</el-button>
        <el-button icon="el-icon-refresh" type="warning" plain @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="customTab" v-loading="loading">
      <el-tabs type="border-card" v-model="actived" @tab-click="tabChange" v-loading="loading">
        <el-tab-pane :label="tab.label" :name="i" v-for="(tab,i) in statesMap" :key="i">
          <div class="table_box" v-if="tableData.records&&tableData.records.length">
            <div class="table_row" v-for="item in tableData.records " :key="item.id">
              <backOrderItem :orderItem="item" userType="guarant">
                <el-button type="text" @click="openDaKuan(item,2)"
                           v-if=" checkPermi(['baopeidingdan:shenqingfangkuan'])&& item.orderStatus == 1&&item.buyerPayStatus==2&&(item.guaranteePayStatus==1||item.guaranteePayStatus==4||!item.guaranteePayStatus)&&(item.guaranteeRefundStatus!=2&&item.guaranteeRefundStatus!=3) && item.orderType !=4">支付截图</el-button>
                <el-button type="text" @click="createContract(item)" v-if="checkPermi(['baopeidingdan:qianshuhetong'])&&item.signContractState==1">签署合同</el-button>
                <el-button type="text" @click="openContract(item.signContractId)" v-if="checkPermi(['baopeidingdan:qianshuhetong'])&&item.signContractState==2&&item.signContractId">查看合同</el-button>
                <el-button type="del" @click="openShouhou(item)" v-if="checkPermi(['baopeidingdan:tijiaoshouhou'])&&item.orderStatus == 4">提交售后</el-button>
                <el-button type="edit" @click="openEditBaopeiInfo(item)" v-if="checkPermi(['baopeidingdan:beopeiziliao'])&&item.orderStatus == 1">包赔资料</el-button>
                <template v-if="item.orderType == 4">
                    <el-button type="add" @click="finishOrder(item)" v-if="checkPermi(['baopeidingdan:finishOrder'])&&item.orderStatus == 1">完成订单</el-button>
                    <el-button type="del" @click="cancelOrder(item)" v-if="checkPermi(['baopeidingdan:cancelOrder'])&&item.orderStatus == 1">取消交易</el-button>
                  </template>
                  <template v-else>
                      <el-button type="add" @click="finishOrder(item)" v-if="checkPermi(['baopeidingdan:finishOrder'])&&item.orderStatus == 1&&item.buyerPayStatus==2&&item.guaranteePayStatus==2">完成订单</el-button>
                    <el-button type="del" @click="cancelOrder(item)" v-if="checkPermi(['baopeidingdan:cancelOrder'])&&item.orderStatus == 1&&(item.buyerPayStatus!=2||(item.buyerPayStatus==2&&item.guaranteeRefundStatus==2))">取消交易</el-button>
                  </template>
                <!-- <el-button type="del" @click="openDaKuan(item,3)"
                           v-if="checkPermi(['baopeidingdan:shenqingtuikuan'])&&item.orderStatus == 1&&item.buyerPayStatus==2&&(item.guaranteeRefundStatus==1||item.guaranteeRefundStatus==4||!item.guaranteeRefundStatus)&&(item.guaranteePayStatus!=2&&item.guaranteePayStatus!=3)">申请退款</el-button> -->
              
                <el-button type="text" v-if="checkPermi(['baopeidingdan:viewOrder'])" @click="openOrderDetail(item)">订单详情</el-button>
                <el-button type="del" v-if="checkPermi(['baopeidingdan:jiesanqunzu'])&&item.toGroup" @click="cancelGroupIM(item.id)">解散群组</el-button>
                <el-button type="text" v-if="checkPermi(['baopeidingdan:huifuqunzu'])&&item.msgGroupInfoId&&!item.toGroup" @click="recoveryGroup(item.id)">恢复群组</el-button>
              </backOrderItem>
            </div>
          </div>
          <div v-else>
            <el-empty description="暂无数据"></el-empty>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div class="pages-box">
      <pagination v-show="tableData.total > 0" :total="tableData.total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </div>

    <!-- <selectBaopei ref="selectBaopei" @pullBaopeiSure="pullBaopeiSure"></selectBaopei> -->

    <!--  2023 12 04 新增 -->
    <orderDetailDialog ref="orderDetailDialog"></orderDetailDialog>
    <editPriceDialog ref="editPriceDialog"></editPriceDialog>
    <shenQingDakuanDialog ref="shenQingDakuanDialog"></shenQingDakuanDialog>
    <baopeiEditDialog ref="baopeiEditDialog"></baopeiEditDialog>
    <shenQingShouhouDialog ref="shenQingShouhouDialog"></shenQingShouhouDialog>
    <finishOrderDialog ref="finishOrderDialog"></finishOrderDialog>

     <!-- 创建合同弹窗 -->
     <createContract ref="createContractRef"></createContract>
      <!-- 店铺认证弹窗 -->
    <authDialog ref="authDialog"></authDialog>
    <!-- <billDetail ref="billDetail"></billDetail> -->
  </div>
</template>

<script>
import supplyConfigApi from "@/api/system/supplyConfig";
import orderDetailDialog from "../recycleManage/components/orderDetailDialog.vue";

import editPriceDialog from "../recycleManage/components/editPrice.vue";
import onSelfApi from "@/api/retrieveManage/onSelf.js";
import gameListApi from "@/api/gameConfig/gameList";
import { getDicts } from "@/api/system/dict/data";
import Cookies from "js-cookie";
import openWindownFn from "@/utils/openUrlByWindow.js";
import backOrderItem from "../recycleManage/components/backOrderItem.vue";
import shenQingDakuanDialog from "../recycleManage/components/shenQingDakuanDialog.vue";
import baopeiEditDialog from "../recycleManage/components/baopeiInfo.vue";
import shenQingShouhouDialog from "../recycleManage/components/shenQingShouhouDialog.vue";

import finishOrderDialog from "../recycleManage/components/finishOrderDialog.vue";
// 创建合同
import createContract from "../../aiqian/createContract.vue";
import authDialog from "@/views/tenantPages/shopManage/shopCenter/authDialog";

// shenQingShouhouDialog
export default {
  name: "",
  components: {
    backOrderItem,
    orderDetailDialog,
    editPriceDialog,
    shenQingDakuanDialog,
    baopeiEditDialog,
    shenQingShouhouDialog,
    finishOrderDialog,
    createContract,
    authDialog,
  },
  data() {
    return {
      statesMap: {
        0: {
          label: "全部",
          type: "",
        },
        1: {
          label: "交易中",
          type: "",
        },
        // 2: {
        //   label: "待审核",
        //   type: "warning",
        // },
        // 3: {
        //   label: "已审核",
        //   type: "success",
        // },
        4: {
          label: "交易完成",
          type: "success",
        },
        5: {
          label: "交易失败",
          type: "danger",
        },
      },
      loading: false,
      tableData: {
        records: [],
        total: 0,
      },
      actived: "0",
      gameList: [],
      timer: [],
      successTimer: [],
      errorTimer: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        accountNumber: "",
        dataType: "guarant",
        createTimeStart: "",
        createTimeEnd: "",
        gameId: "",
        no: "",
        orderStatus: "",
        guaranteeId:''
      },
      currentData: {},
      IMhost: "",
      exportloading: false,
      yuangongList:[]
    };
  },
  created() {
    this.getList();
    // this.getIMhost()
    this.getGameList();
    this.getYuangongList()
    // this.getHost();
  },
  computed: {
    tenantInfo() {
      return this.$store.getters.shopInfo;
    },
  },
  methods: {
    // 获取订单列表
    getList() {
      this.loading = true;
      if (this.timer && this.timer.length) {
        this.queryParams.createTimeStart = this.timer[0];
        this.queryParams.createTimeEnd = this.timer[1] + " " + "23:59:59";
      } else {
        this.queryParams.successTimeStart = "";
        this.queryParams.successTimeEnd = "";
      }
      if (this.tenantInfo) {
        this.queryParams.operatorTenantId = this.tenantInfo.tenantId;
      }
      onSelfApi.getbackClueOrderList(this.queryParams).then((response) => {
        this.tableData.records = [];
        this.tableData.records = response.rows;
        this.tableData.total = response.total;
        this.loading = false;
      });
    },
     // 获取所有员工列表
    getYuangongList() {
      supplyConfigApi
        .getAllUserList({
          userNewType: 1,
        })
        .then((res) => {
          this.yuangongList = res.rows;
        });
    },

    // tabs切换时触发
    tabChange(e) {
      // console.log("%c Line:157 🍆 e", "color:#2eafb0", e);
      // this.tableData.records = [];
      this.queryParams.orderStatus = e.name;
      if (e.name == 0) {
        this.queryParams.orderStatus = "";
      }
      this.$nextTick(() => {
        this.resetQuery();
      });
    },
    // 编辑包赔资料弹窗
    openEditBaopeiInfo(row) {
      let flag = "edit";
      this.$refs.baopeiEditDialog.open(row, flag);
    },
    // 打款申请
    openDaKuan(row, flag) {
      // 打开申请打款弹窗
      this.$refs.shenQingDakuanDialog.open(row, flag);
    },
    // 完成换绑
    wanchenghuanbang(row) {
      this.$confirm(
        "完成之前请确认合同是否签署，包赔是否完成，一旦完成将无法撤回,确定完成换绑吗？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          onSelfApi.changeBindState({ id: row.id }).then((res) => {
            this.$message.success(res.msg);
            this.getList();
          });
        })
        .catch(() => {});
    },
    // 完成订单
    finishOrder(row) {
      if (row.guaranteeRefundStatus == 3) {
        return this.$message({
          type: "error",
          message: "订单有退款正在进行中，不能完成交易！",
        });
      }
      //弹出确认完成交易的弹窗
      this.$refs.finishOrderDialog.open(row.id);

      // this.$confirm(
      //   "请确认该回收订单各方均已完成，完成后不可撤销, 是否继续?",
      //   "提示",
      //   {
      //     confirmButtonText: "确定",
      //     cancelButtonText: "取消",
      //     type: "warning",
      //   }
      // )
      //   .then(() => {
      //     let obj = {
      //       id: row.id,
      //     };
      //     onSelfApi.backClueOrderFinishOrder(obj).then((res) => {
      //       this.$message.success(res.msg);
      //       this.getList();
      //     });
      //   })
      //   .catch(() => {});
    },
    // 取消订单
    cancelOrder(row) {
      this.$prompt("请确保资金已妥善处理！请输入取消订单备注", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(({ value }) => {
          let obj = {
            id: row.id,
            remark: row.remark + "\n取消订单备注：" + value,
          };
          onSelfApi.backClueOrderCancelOrder(obj).then((res) => {
            this.$message.success(res.msg);
            this.getList();
          });
        })
        .catch(() => {});

      // this.$confirm(
      //   "如果已支付，取消订单后请自行处理款项，确定取消该订单吗？",
      //   "提示",
      //   {
      //     confirmButtonText: "确定",
      //     cancelButtonText: "取消",
      //     type: "warning",
      //   }
      // )
      //   .then(() => {
      //     onSelfApi.backClueOrderCancelOrder({ id }).then((res) => {
      //       this.$message.success(res.msg);
      //       this.getList();
      //     });
      //   })
      //   .catch(() => {});
    },
    // 解散群组
    cancelGroupIM(id) {
      this.$confirm("此操作将解散该订单的聊天群组, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          onSelfApi.cancelGroup({ id }).then((res) => {
            this.$message.success(res.msg);
            this.getList();
          });
        })
        .catch(() => {});
    },
    // 恢复群组
    recoveryGroup(id) {
      onSelfApi.recoveryGroup({ id }).then((res) => {
        this.$message.success(res.msg);
        this.getList();
      });
    },

    async viewOrder(id) {
      let res = await onSelfApi.byIdForIM({ id });

      this.$refs.addDialog.open("view", res.data);
    },
    // 查看详情
    viewInfo(row) {
      this.$refs.previewBackInfo.open(row.backId);
    },
    // 游戏列表
    getGameList() {
      gameListApi.getGameList().then((res) => {
        this.gameList = res.rows;
      });
    },
    // 获取IM域名
    getIMhost() {
      getDicts("IMhost").then((res) => {
        if (res.code == 200) {
          this.IMhost = res.data[0]?.dictValue;
        }
      });
    },
    // 打开售后提交弹窗
    openShouhou(row) {
      this.$refs.shenQingShouhouDialog.open(row);
    },
  // 签署合同
  createContract(row) {
      this.$confirm("请选择签署合同的方式：", "签署合同", {
        confirmButtonText: "系统生成合同",
        cancelButtonText: "自定义合同",
        type: "warning",
      })
        .then(() => {
          this.loading = true;
          onSelfApi
            .createContract({ id: row.id })
            .then((res) => {
              // console.log("%c Line:341 🍪 res", "color:#b03734", res);
              this.loading = false;
              if (res.code == 200) {
                this.getList();
                if (res.data.id) {
                  this.openContract(res.data.id)
                  // window.open(res.data.jfUrl);
                }
              } else if (res.code == 20012) {
                this.$confirm("店铺还未进行实名认证，是否立即认证？", "提示", {
                  confirmButtonText: "立即认证",
                  cancelButtonText: "取消",
                  type: "warning",
                })
                  .then(() => {
                    // this.$router.push("/shopManageByTenant/shopCenter");
                    this.$refs.authDialog.open();
                  })
                  .catch((err) => {});
              }
            })
            .catch(() => {
              this.loading = false;
            });
        })
        .catch(() => {
          // 拉起创建合同弹窗
          this.openAddHetong(row)
          this.loading = false;
        });
    },
    // 打开创建合同的弹窗
    openAddHetong(row) {
      this.$refs.createContractRef.open(row,2);
    },
    // 查看合同
    openContract(id) {
      this.$refs.viewContract.open(id);
      // onSelfApi.getContractUrl(row.signContractId).then((res) => {
      //   if (res.data.purchaserUrl) {
      //     window.open(res.data.purchaserUrl);
      //   }
      //   // if (res.data.purchaserUrl) {
      //   //   window.open(res.data.purchaserUrl);
      //   // }
      // });
    },
    // 跳转IM页面
    // goIM(IMid) {
    //   let token = Cookies.get('Admin-Token')
    //   // window.open(`${this.IMhost}/chat/conversation?hxuser=${IMid}&str=${token}&chatType=groupChat`)

    // },
    // 跳转客服系统
    goIM(IMid, chatType) {
      if (IMid) {
        let token = Cookies.get("Admin-Token");
        openWindownFn.openWindown(
          `${this.IMhost}/chat/conversation?hxuser=${IMid}&str=${token}&chatType=${chatType}`,
          "addFileWindow",
          "depended=no,toolbar=no,location=no,resizable=no, height=700, width=1280,,scrollbars=yes ,left=380,top=100"
        );
      } else {
        this.$message.error("该订单没有群聊！");
      }
    },

    // 搜索
    search() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 打开订单详情
    openOrderDetail(row) {
      this.$refs.orderDetailDialog.open(row.id);
    },
    // 改价
    gaijia(row) {
      this.$refs.editPriceDialog.open(row, "buyer");
    },
    // 一键拉群  卖家  回收商  于都客服
    groupChats(row) {
      this.$confirm("卖家和回收商确认交易该账号后再拉群, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          onSelfApi.createGroupRoom(row).then((res) => {
            if (res.code == 200) {
              this.$alert(res.data.message);
            } else {
              this.$alert(res.msg);
            }
            this.getList();
          });
        })
        .catch(() => {});
    },

    // 拉包赔进群  打开选择包赔
    pullBaopei(row) {
      // 打开包赔商选择框
      this.currentData = row;
      this.$refs.selectBaopei.open();
    },
    // 确认拉包赔进群
    pullBaopeiSure(cpsId) {
      let params = {
        id: this.currentData.id,
        guaranteeId: cpsId,
      };
      onSelfApi.pullBaopeiGroup(params).then((res) => {
        if (res.code == 200) {
          this.$alert(res.msg);
        } else {
          this.$alert(res.msg);
        }
        this.getList();
      });
    },
    // 打开编辑弹窗 完成或者取消
    editOrder(row, status, type) {
      this.$refs.addDialog.open(row, status, type);
    },
    // 打开查看弹窗
    viewPhone(row) {
      this.$refs.viewPhone.open(row);
    },
    //重置
    resetQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.accountNumber = "";
      this.queryParams.createTimeStart = "";
      this.queryParams.createTimeEnd = "";
      this.queryParams.gameId = "";
      this.queryParams.no = "";
      this.timer = [];
      this.successTimer = [];
      this.errorTimer = [];
      this.getList();
    },
  },
};
</script>
<style lang="scss" scoped>
.table_box {
  padding: 0 !important;
  box-shadow: none !important;
}
</style>